package com.ia.aistream.manager.operating.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ia.aistream.manager.framework.util.ShiroUtils;
import com.ia.aistream.manager.operating.conf.DocMapConf;
import com.ia.aistream.manager.operating.util.style.DocStyleUtil;
import com.ia.aistream.manager.operating.util.style.DocTableStyle;
import com.ia.aistream.manager.operating.util.tools.DocToolUtil;
import com.ia.aistream.model.operating.dto.convert.ConvertDto;
import com.ia.aistream.model.operating.entity.DocAppendix;
import com.ia.aistream.model.operating.entity.DocApproval;
import com.ia.aistream.model.operating.entity.DocRev;
import com.ia.aistream.model.operating.dto.ColumnStyle;
import com.ia.aistream.model.operating.entity.DocTitle;
import com.spire.doc.*;
import com.spire.doc.collections.DocumentObjectCollection;
import com.spire.doc.documents.DocumentObjectType;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.fields.DocPicture;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author XiaoYu
 */
public class DocIndex {

    /*****
     * 获取文档修改记录信息
     * @param s
     * @throws Exception
     */
//    public static List<DocRev> docTracking(Section s, Long fid) throws Exception{
    public static Map<String, Object> docTracking(Section s, Long fid, String fileName, String ext, int imgNum, int titleIndex, int appParIndex) throws Exception{
        DocumentObjectCollection docs = s.getBody().getChildObjects();
        Map<String, Object> result = new HashMap();
        List<DocRev> docTrackingList = new ArrayList<>();
        boolean flag = false;
        boolean mergin = false;
        boolean fla = true;
        for(int i=0;i<docs.getCount(); i++){
            if(docs.get(i).getDocumentObjectType().equals(DocumentObjectType.Table)){
                if(fla){
                    Table table = (Table) docs.get(i);
                    // 循环行
                    for(int r=0; r<table.getRows().getCount(); r++){

                        DocRev docTracking = null;

                        // 循环列
                        for(int c=0; c<table.getRows().get(r).getCells().getCount(); c++){
                            // 获取列中的内容
                            String trim = "";
                            TableCell tableCell = table.getRows().get(r).getCells().get(c);
                            // 循环段落
                            for(int p=0; p<table.getRows().get(r).getCells().get(c).getParagraphs().getCount(); p++){
                                String listText = table.getRows().get(r).getCells().get(c).getParagraphs().get(p).getListText().trim();
                                // 处理单元格中的内容
                                trim = trim +  listText + table.getRows().get(r).getCells().get(c).getParagraphs().get(p).getText().trim();
                            }

                            if(trim.equals("")){
                                continue;
                            }
                            // 获取合并几行
                            Integer  rowsMerge = DocTableStyle.getRowsMerge(table, r, c);
                            ColumnStyle columnStyle = DocStyleUtil.revStyle(tableCell);

                            // 给属性赋值
                            columnStyle.getTdInfo().setRowMerge(rowsMerge);
                            JSONObject cellStyle = (JSONObject)JSONObject.toJSON(columnStyle);
                            if(handleNum(trim) && trim.length()==3){
                                // 创建对象
                                docTracking = new DocRev();
                                flag = true;
                            }
                            if(flag){

                                switch(c){
                                    case 0:
                                        docTracking.setVersion(trim);
                                        docTracking.setVersionStyle(cellStyle);
                                        break;
                                    case 1:
                                        if(handleNum(trim)){
                                            docTracking.setEdition(trim);
                                            docTracking.setEditionStyle(cellStyle);
                                        }else{
                                            mergin = true;
                                            flag = false;
                                            docTracking.setCompile(trim);
                                            docTracking.setCompileStyle(cellStyle);
                                        }
                                        break;
                                    case 2:
                                        docTracking.setCompile(trim);
                                        docTracking.setCompileStyle(cellStyle);
                                        break;
                                    case 3:
                                        docTracking.setApproval(trim);
                                        docTracking.setApprovalStyle(cellStyle);
                                        break;
                                    case 4:
                                        docTracking.setApprovalDate(trim);
                                        docTracking.setApprovalDateStyle(cellStyle);
                                        break;
                                    case 5:
                                        docTracking.setModifyExplain(trim);
                                        docTracking.setModifyExplainStyle(cellStyle);
                                        break;
                                    default:
                                }
                            }
                            if(mergin){
                                switch(c){
                                    case 2:
                                        docTracking.setApproval(trim);
                                        docTracking.setApprovalStyle(cellStyle);
                                        break;
                                    case 3:
                                        docTracking.setApprovalDate(trim);
                                        docTracking.setApprovalDateStyle(cellStyle);
                                        break;
                                    case 4:
                                        docTracking.setModifyExplain(trim);
                                        docTracking.setModifyExplainStyle(cellStyle);
                                        break;
                                    default:

                                }
                            }
                        }
                        if(docTracking != null){
                            docTracking.setDocIndexId(fid);
                            docTracking.setCreateBy(ShiroUtils.getLoginName());
                            docTracking.setCreateTime(new Date());
                            docTrackingList.add(docTracking);
                        }
                        flag = false;
                        mergin = false;
                    }
                }
            }else if(docs.get(i).getDocumentObjectType().equals(DocumentObjectType.Paragraph)){
                Paragraph paragraph = (Paragraph)docs.get(i);
                String trim = paragraph.getText().trim().replace(" ", "");
                if(trim.equals("目录")){
                    flag = false;
                }
                // 目录
                Map<String, Object> map = DocFileData.tableOrParagraph(s, i, fid, null, null, null, fileName, imgNum, "目录", 0, null, titleIndex, appParIndex);
                map.put(DocMapConf.DOC_REV_LIST.value, docTrackingList);
                return map;

//                System.out.println("暂未处理....");
//                System.out.println(paragraph.getText());
            }
        }
        result.put(DocMapConf.DOC_REV_LIST.value, docTrackingList);
        return result;
    }


    /**
     * 处理文件的索引信息（文档第一页）
     * @param s
     * @param fileName
     * @param ext
     * @param imgNum 表示文档中图片的顺序
     * @return
     * @throws IOException
     */
    public static Map<String, Object> docIndex(Section s, String fileName, String ext, int imgNum) throws IOException {
        Map<String, Object> map = new HashMap<>();
        DocApproval docApproval = new DocApproval();
        com.ia.aistream.model.operating.entity.DocIndex docIndex = new com.ia.aistream.model.operating.entity.DocIndex();
        int index=-5;
        // 处理文件审批信息
        boolean flag = false;
        // 处理质量信息
        boolean qFlag = false;
        // 处理质量等级
        String quLevel = "";
        String content = "";
        // 处理质量级别样式
        List<JSONObject> objList = new ArrayList<>();

        DocumentObjectCollection docs = s.getBody().getChildObjects();
        // 遍历文档中含有的对象
        for (int i=0; i<docs.getCount(); i++){
            // 判断对象类型
            if(docs.get(i).getDocumentObjectType().equals(DocumentObjectType.Table)) {
                // 转型为Table
                Table table = (Table) docs.get(i);
                // 循环处理行
                for(int r=0; r<table.getRows().getCount(); r++){
                    if(r==index+2){
                        flag = true;
                    }
                    // 获取最大列
                    int cols = table.getRows().get(r).getCells().getCount();
                    for(int c=0; c<cols; c++){
                        String trim = "";

                        int pCount = table.getRows().get(r).getCells().get(c).getParagraphs().getCount();
                        for(int j=0; j< pCount; j++){
                            String parText = table.getRows().get(r).getCells().get(c).getParagraphs().get(j).getText().trim();
                            trim = trim + parText;
                        }
                        // 获取合并单元格数量
                        Integer rowsMerge = DocTableStyle.getRowsMerge(table, r, c);
                        // 获取单元格样式
                        ColumnStyle columnStyle = DocStyleUtil.tableCellStyle(table.getRows().get(r).getCells().get(c));
                        columnStyle.getTdInfo().setRowMerge(rowsMerge);
                        JSONObject cellStyle = (JSONObject)JSONObject.toJSON(columnStyle);
                        // 处理文件索引信息
                        if(r==0 && c==0){
                            String companyLogo = fileName.substring(0, fileName.lastIndexOf("/")+1) + fileName.substring(fileName.lastIndexOf("_")+1);
                            companyLogo = companyLogo.replace("."+ext, "_logo.png");

                            int count = table.getRows().get(r).getCells().get(c).getChildObjects().get(0).getChildObjects().getCount();
                            for(int p=0; p<count;p++){
                                DocumentObject documentObject = table.getRows().get(r).getCells().get(c).getChildObjects().get(0).getChildObjects().get(p);
                                if(documentObject instanceof DocPicture){
                                    imgNum++;
                                    DocPicture docPicture = (DocPicture)documentObject;
                                    DocToolUtil.downloadImages(docPicture, companyLogo);
                                    docIndex.setFileLogo("/profile" + companyLogo.substring(companyLogo.indexOf("/" + ext)));
                                }
                            }
                            continue;
                        }else if(r==0 && c==1){
                            docIndex.setFileType(trim);
                            docIndex.setFileTypeStyle(cellStyle);
                            continue;
                        }

                        // 如果是空则继续循环
                        if (trim.equals("")){
                            continue;
                        }
                        // 处理文件名称
                        if(table.getRows().get(r).getCells().getCount()==1 && trim.endsWith("规程")){
                            docIndex.setFileName(trim);
                            docIndex.setFileNameStyle(cellStyle);
                            continue;
                        }
                        // 处理文件编码
                        if(trim.startsWith("FQ")){
                            docIndex.setFileCode(trim);
//                            String replace = columnStyle.toString().replace("<br />", "");
//                            docIndex.setFileCodeStyle((JSONObject) JSON.parse(replace));
                            docIndex.setFileCodeStyle(cellStyle);
                            continue;
                        }
                        // 处理版本，版次信息
                        if(trim.contains("版本")){
                            String version = "";
                            if(trim.contains("版次")){
                               version = trim.substring(trim.indexOf("：") + 1, trim.indexOf("版次"));
                            }else{
                                version = trim.substring(trim.indexOf("：") + 1);
                            }

                            docIndex.setFileVersion(version);
                            docIndex.setFileVersionStyle(cellStyle);
                            // 判断制定表格的段落数
                            int count = table.getRows().get(r).getCells().get(c).getParagraphs().getCount();
                            if(count>1){
                                String edition = table.getRows().get(r).getCells().get(c).getParagraphs().get(1).getText().trim();
                                docIndex.setFileEdition(edition.substring(edition.indexOf("：")+1));
                            }
                            continue;
                        }
                        // 处理总页数
                        if("总页数：".equals(trim)){
                            docIndex.setFilePages(table.getRows().get(r).getCells().get(c+1).getParagraphs().get(0).getText().trim());
                            docIndex.setFilePagesStyle(DocStyleUtil.getColumnStyle(table, r, c+1));
                            continue;
                        }
                        // 处理附录数
                        if("附录数：".equals(trim)){
                            docIndex.setFileAppendix(table.getRows().get(r).getCells().get(c+1).getParagraphs().get(0).getText().trim());
                            docIndex.setFileAppendixStyle(DocStyleUtil.getColumnStyle(table, r, c+1));
                            continue;
                        }

                        // 处理文件升版原因
                        if(trim.contains("升版原因")){
                            // 判断制定表格的段落数
                            int count = table.getRows().get(r).getCells().get(c).getParagraphs().getCount();
                            if(count > 1){
                                for(int p=1;p<count;p++){
                                    trim = trim + "-" + table.getRows().get(r).getCells().get(c).getParagraphs().get(p).getText().trim();
                                }
                            }
                            docIndex.setUpgradeReason(trim);
                            docIndex.setUpgradeReasonStyle(cellStyle);
                            continue;
                        }
                        // 处理批准实施
                        if("批准实施：".equals(trim)){
                            String appImg =  fileName.substring(0, fileName.lastIndexOf("/")+1) + fileName.substring(fileName.lastIndexOf("_")+1);
                            appImg = appImg.replace("." + ext, "_approval.png");
                            int count = table.getRows().get(r).getCells().get(c + 1).getChildObjects().get(0).getChildObjects().getCount();
                            for(int p=0; p<count; p++){
                                DocumentObject object = table.getRows().get(r).getCells().get(c + 1).getChildObjects().get(0).getChildObjects().get(p);
                                if(object instanceof DocPicture){
                                    imgNum++;
                                    DocPicture docPicture = (DocPicture) object;
                                    DocToolUtil.downloadImages(docPicture, appImg);
                                    docIndex.setApproval("/profile" + appImg.substring(appImg.indexOf("/"+ext)));
                                }
                            }
                            continue;
                        }

                        // 处理批准日期
                        if("批准日期：".equals(trim)){
                            docIndex.setApprovalDate(table.getRows().get(r).getCells().get(c+1).getParagraphs().get(0).getText().trim());
                            docIndex.setApprovalDateStyle(DocStyleUtil.getColumnStyle(table, r, c+1));
                            continue;
                        }

                        // 处理质量级别
                        if(qFlag){
                            quLevel = quLevel + "-" + trim;
                            objList.add(cellStyle);
                        }

                        if("质量级别：".equals(trim) || trim.startsWith("执行等级：")){
                            qFlag = true;
                            content = trim;
                            continue;
                        }
                        if(qFlag && c==cols-2){
                            qFlag = false;
                            if(content.startsWith("执行等级：")){
                                docIndex.setRunLevel(quLevel.substring(1));
                                docIndex.setRunLevelStyle((JSONArray)JSONArray.toJSON(objList));
                            }else{
                                docIndex.setQualityLevel(quLevel.substring(1));
                                docIndex.setQualityLevelStyle((JSONArray)JSONArray.toJSON(objList));
                            }
                            docIndex.setFileHistoryCode(table.getRows().get(r).getCells().get(c+1).getParagraphs().get(0).getText().trim());
                            docIndex.setFileHistoryCodeStyle(DocStyleUtil.getColumnStyle(table, r, c+1));
                            continue;
                        }
                        // 处理下次审查时间和文件存放位置
                        if("下次审查升版时间：".equals(trim)){
                            docIndex.setUpgradeTime(table.getRows().get(r).getCells().get(c+1).getParagraphs().get(0).getText().trim());
                            docIndex.setUpgradeTimeStyle(DocStyleUtil.getColumnStyle(table, r, c+1));
                            if(cols==c+3){
                                docIndex.setFileLocation(table.getRows().get(r).getCells().get(c+2).getParagraphs().get(0).getText().trim());
                                docIndex.setFileLocationStyle(DocStyleUtil.getColumnStyle(table, r, c+2));
                            }
                            continue;
                        }
//                         处理规程执行等级
                        if(trim.startsWith("规程执行等级")){
                            docIndex.setRunLevel(trim);
                            List runLevel = new ArrayList();
                            runLevel.add(cellStyle);
                            docIndex.setRunLevelStyle((JSONArray) JSONArray.toJSON(runLevel));
                            continue;
                        }
                        // 处理分发部门
                        if(trim.contains("处")){
                            int count = table.getRows().get(r).getCells().get(c).getParagraphs().getCount();
                            for(int p=0;p<count;p++){
                                String depart = "-" + table.getRows().get(r).getCells().get(c).getParagraphs().get(p).getText().trim();
                                if(depart.contains("分发")){
                                    docIndex.setDistribute(depart.substring(depart.indexOf("：")+1));
                                    docIndex.setDistributeStyle(cellStyle);
                                }
                            }
                            continue;
                        }
                        if ("编写".equals(trim)){
                            index = r;
                        }
                        if(flag){
                            switch (c){
                                case 0:
                                    docApproval.setCompileDate(trim);
                                    docApproval.setCompileDateStyle(cellStyle);
                                    break;
                                case 1:
                                    docApproval.setCompileName(trim);
                                    docApproval.setCompileNameStyle(cellStyle);
                                    break;
                                case 2:
                                    docApproval.setCompileSign(trim);
                                    docApproval.setCompileSignStyle(cellStyle);
                                    break;
                                case 3:
                                    docApproval.setCheckName(trim);
                                    docApproval.setCheckNameStyle(cellStyle);
                                    break;
                                case 4:
                                    docApproval.setCheckSign(trim);
                                    docApproval.setCheckSignStyle(cellStyle);
                                    break;
                                case 5:
                                    docApproval.setExaminedName(trim);
                                    docApproval.setExaminedNameStyle(cellStyle);
                                    break;
                                case 6:
                                    docApproval.setExaminedSignDate(trim);
                                    docApproval.setExaminedSignDateStyle(cellStyle);
                                    break;
                                case 7:
                                    docApproval.setCountersign(trim);
                                    docApproval.setCountersignStyle(cellStyle);
                                    break;
                                default:
                                    break;
                            }
                        }
                    }
                    flag = false;
                }
            }
        }

        // 将处理的对象，封装到map集合
        map.put(DocMapConf.DOC_INDEX_APPROVAL.value, docApproval);
        map.put(DocMapConf.DOC_INDEX.value, docIndex);
        map.put(DocMapConf.DOC_IMG_NUM.value, imgNum);
        return map;
    }


    /***
     * 获取表格的内容
     * @param tableCell
     * @return
     */
    public static String getCellContent(TableCell tableCell){
        String str = "";
        for(int p=0; p<tableCell.getParagraphs().getCount(); p++){
            str = str + tableCell.getParagraphs().get(p).getListText() + "  " + tableCell.getParagraphs().get(p).getText().trim();
        }
        return str.trim();
    }

    /***************************************************  私有化方法  *******************************/

    /***
     * 处理部门数据
     * @param depart
     * @return
     */
    private static List<String> handDepart(String depart){
        // 获取需要分发的部门
        String departs = depart.substring(depart.indexOf("：")+1).trim();
        String[] dep = departs.split("、");
        return Arrays.asList(dep);
    }

    /***
     * 判断字符串是不是数字
     * @param msg
     * @return
     */
    private static boolean handleNum(String msg){
        String pat = "^[0-9]*$";
        Pattern rtb = Pattern.compile(pat);
        Matcher mtb = rtb.matcher(msg);
        return mtb.matches();
    }

}
